package com.xuyh.pdf.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.joda.time.DateTime;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.*;

public class NetData {


    public static void main(String[] args) throws Exception {
        remoteData();
        processData();
    }

    private static void processData() throws Exception {
        FileInputStream inputStream = new FileInputStream("D:\\detail.txt");
        int available = inputStream.available();
        byte[] bytes = new byte[available];
        inputStream.read(bytes);
        JSONArray array = JSON.parseArray(new String(bytes));
        Map<String, JSONArray> map = new TreeMap<>(String::compareTo);

        for (int i = 0; i < array.size(); i++) {
            JSONObject item = array.getJSONObject(i);
            JSONObject body = item.getJSONObject("body");
            Date bizDate = body.getDate("bizDate");
            DateTime dateTime = new DateTime(bizDate);
            String yearMonth = dateTime.toString("yyyy-MM");
            JSONArray list = map.get(yearMonth);
            JSONArray cargoBaseVOList = body.getJSONArray("cargoBaseVOList");
            if (list == null) {
                list = new JSONArray();
                map.put(yearMonth, list);
            }
            list.addAll(cargoBaseVOList);
        }

        writeData(JSON.toJSONString(map), "ddd");
    }


    private static void remoteData() throws Exception {
        String cookie = "DEVICEID=219FeE34-50FA-4ba8-be60-04e628c744aC";
        String ucSessionId = "IRDg8HbR9c09730100030000";
        List<JSONObject> tmp = new ArrayList<>();
        JSONArray list = getList(cookie, ucSessionId);
        writeData(JSON.toJSONString(list), "list");
        for (int i = 0; i < list.size(); i++) {
            JSONObject detail = list.getJSONObject(i);
            Thread.sleep(500);
            try {
                JSONObject result = getDetail(cookie, ucSessionId, detail.getString("invoiceId"));
                tmp.add(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        writeData(JSON.toJSONString(tmp), "detail");
    }

    private static void writeData(String data, String fileName) throws Exception {
        File file = new File("D:\\" + fileName + ".txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PrintWriter printWriter = new PrintWriter(fileOutputStream);
        printWriter.write(data);
        printWriter.close();
        fileOutputStream.close();
    }

    private static JSONObject getDetail(String cookie, String ucSessionId, String id) {
        String url = "https://www.fapiao56.com/invoice-web/invoice/output/general/detail?customerId=351594612829280&id=" + id + "&_=1650119657764";
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET, getHeader(cookie, ucSessionId), JSONObject.class);
        return responseEntity.getBody();
    }

    private static JSONArray getList(String cookie, String ucSessionId) {
        String url = "https://www.fapiao56.com/invoice-web/invoice/output/list";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject params = new JSONObject();
        params.put("beginDate", "2021-10-01");
        params.put("endDate", "2021-10-31");
        params.put("page", "1");
        params.put("pageSize", "999");
        params.put("customerId", "351594612829280");
        params.put("areaCode", "650103");
        params.put("withComplement", "1");
        params.put("ignoreRiskDetail", "1");
        params.put("sortName", "biz_date");
        HttpEntity<Object> entity = getHeader(cookie, ucSessionId, params);
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        return body.getJSONArray("body");
    }


    private static HttpEntity<Object> getHeader(String cookie, String ucSessionId, Map<String, Object> params) {
        HttpHeaders headers = new HttpHeaders();
        List<String> cookies = new ArrayList<>();
        cookies.add(cookie);
        headers.put(HttpHeaders.COOKIE, cookies);
        headers.put("ucSessionId", Arrays.asList(new String[]{ucSessionId}.clone()));
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new HttpEntity<>(params, headers);
    }

    private static HttpEntity<Object> getHeader(String cookie, String ucSessionId) {
        return getHeader(cookie, ucSessionId, null);
    }
}
